/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mail.server;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;
import mail.attribute.MailItem;
import mail.attribute.attach.Attachment;
import mail.attribute.attach.AttachmentsList;
import mail.general.FileUtils;

/**
 *
 * @author timoteo
 */
public class MailItemWriter {

    private static final Logger logger = Logger.getLogger(MailItemWriter.class.getName());
    private final String folderPath;

    public MailItemWriter(String folderPath) {
        this.folderPath = folderPath;
    }

    public void save(MailItem item) {
        Writer output = null;
        File file = null;
        try {
            File dir = new File(folderPath + "/" + item.getTo().toString());
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String text = item.getMessage().getMessage().toString();
            file = new File(folderPath + "/" + item.getTo().toString() + "/" + (item.getDate().getTime()) + ".txt");
            file.createNewFile();
            output = new BufferedWriter(new FileWriter(file));
            output.write("0");
            output.write("$");
            output.write(item.getFrom().toString());
            output.write("$");
            output.write(PersistentMailBox.DATE_FORMAT.format(item.getDate()));
            output.write("$");
            output.write(item.getSubject());
            output.write("$");
            output.write(text);
            output.flush();
            saveAttachments(file, item.getMessage().getAttachs());
            logger.info("Message saved : " + file.getAbsolutePath());
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        } finally {
            FileUtils.close(output);

        }
    }

    private void saveAttachments(File file, AttachmentsList attachmentsList) throws FileNotFoundException, IOException {
        for (Attachment attachment : attachmentsList.getAttachmentsList()) {
            saveAttachment(file, attachment);
        }
    }

    private void saveAttachment(File file, Attachment attachment) throws FileNotFoundException, IOException {
        File parent = file.getParentFile();
        FileOutputStream outputStream = null;
        try {
            File newFile = new File(parent.getPath() + "/attachments/" + file.getName() + "_" + attachment.getFileName());
            newFile.getParentFile().mkdirs();
            newFile.createNewFile();
            outputStream = new FileOutputStream(newFile);
            outputStream.write(attachment.getData());
            outputStream.flush();
        } finally {
            FileUtils.close(outputStream);
        }
    }

    public void delete(final File fileToDelete) {
        if (!fileToDelete.exists()) {
            throw new IllegalStateException("File not found : " + fileToDelete.getAbsolutePath());
        }
        fileToDelete.delete();
        deleteAttachments(fileToDelete);
        logger.info("Message deleted : " + fileToDelete.getAbsolutePath());
    }

    private void deleteAttachments(final File fileToDelete) {
        File[] attachments = new File(fileToDelete.getParentFile().getPath() + "/attachments/").listFiles(new FileFilter() {

            @Override
            public boolean accept(File file) {
                return file.getName().startsWith(fileToDelete.getName());
            }
        });
        if (attachments != null) {
            for (File file : attachments) {
                file.delete();
            }
        }
    }
}
